<template>
  <div class="movie-list-container">
    <h2>Popular Movies</h2>
    
    <div class="search-filter">
      <div class="search-box">
        <input
          type="text"
          v-model="searchQuery"
          placeholder="Search movies..."
          @input="debounceSearch"
        />
        <button class="search-btn">
          <i class="search-icon">🔍</i>
        </button>
      </div>
      
      <div class="filter-buttons">
        <button 
          v-for="(genre, index) in genres" 
          :key="index" 
          class="filter-btn" 
          :class="{ active: selectedGenre === genre }"
          @click="selectedGenre = genre"
        >
          {{ genre }}
        </button>
      </div>
    </div>
    
    <div class="movie-grid">
      <div 
        v-if="!movies.length && !isLoading"
        class="no-movies"
      >
        <p>No movies found. {{ isLoggedIn ? 'Be the first to add one!' : 'Login to add movies.' }}</p>
      </div>
      
      <div 
        v-else-if="isLoading"
        class="loading"
      >
        <p>Loading movies...</p>
      </div>
      
      <MovieCard 
        v-else 
        v-for="movie in filteredMovies" 
        :key="movie.id" 
        :movie="movie"
        @view-movie="$emit('view-movie', movie.id)"
        @add-comment="$emit('add-comment', movie.id)"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useUserStore } from '@/stores/user';
import MovieCard from './MovieCard.vue';
import apiService from '@/services/api';

const store = useUserStore();
const isLoggedIn = computed(() => store.isLoggedIn);

const movies = ref([]);
const isLoading = ref(false);
const searchQuery = ref('');
const selectedGenre = ref('All');
const genres = ['All', 'Action', 'Adventure', 'Comedy', 'Drama', 'Fantasy', 'Horror', 'Sci-Fi', 'Thriller'];

// 延迟搜索功能
const debounceSearch = () => {
  clearTimeout(debounceTimeout);
  debounceTimeout = setTimeout(() => {
    if (searchQuery.value === '') {
      fetchMovies();
    }
  }, 300);
};

let debounceTimeout;

const fetchMovies = async () => {
  isLoading.value = true;
  
  try {
    const response = await apiService.getMovies();
    movies.value = response;
  } catch (error) {
    console.error('Failed to fetch movies:', error);
  } finally {
    isLoading.value = false;
  }
};

onMounted(fetchMovies);

// 监听路由变化
watch(
  () => selectedGenre.value,
  (newGenre) => {
    if (newGenre === 'All') {
      fetchMovies();
    }
  }
);

const filteredMovies = computed(() => {
  if (!movies.value.length) return [];
  
  return movies.value.filter(movie => {
    // 过滤搜索结果
    const matchesSearch = searchQuery.value
      ? movie.title.toLowerCase().includes(searchQuery.value.toLowerCase())
      : true;
    
    // 过滤商品类型
    const matchesGenre = selectedGenre.value === 'All' || movie.genre === selectedGenre.value;
    
    return matchesSearch && matchesGenre;
  });
});

// 定义事件
const emit = defineEmits(['view-movie', 'add-comment']);
</script>

<style scoped>
.movie-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.movie-list-container h2 {
  color: #1a1a2e;
  margin-bottom: 20px;
  font-size: 1.8rem;
}

.search-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 25px;
}

.search-box {
  flex: 1;
  display: flex;
  max-width: 400px;
}

.search-box input {
  flex: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
  font-size: 16px;
}

.search-btn {
  background-color: #e94560;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  padding: 0 15px;
  cursor: pointer;
  font-size: 16px;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 20px;
  background-color: white;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.filter-btn.active {
  background-color: #e94560;
  color: white;
  border-color: #e94560;
}

.movie-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.no-movies, .loading {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.no-movies p, .loading p {
  color: #666;
  font-size: 1.1rem;
}

@media (max-width: 768px) {
  .movie-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-box {
    max-width: none;
  }
}

@media (max-width: 480px) {
  .movie-grid {
    grid-template-columns: 1fr;
  }
}
</style>